<template>
  <div class="conversation-sidebar">
    <!-- 侧边栏头部 -->
    <div class="sidebar-header">
      <div class="header-title">
        <HistoryOutlined class="header-icon" />
        <span class="title-text">历史对话</span>
      </div>
      <div class="header-actions">
        <a-button 
          type="text" 
          size="small" 
          @click="refreshConversations"
          :loading="loading"
          class="refresh-btn"
        >
          <template #icon>
            <ReloadOutlined />
          </template>
        </a-button>
      </div>
    </div>

    <!-- 搜索框 -->
    <div class="search-container">
      <a-input
        v-model:value="searchKeyword"
        placeholder="搜索对话..."
        size="medium"
        class="search-input"
        @input="handleSearch"
      >
        <template #prefix>
          <SearchOutlined class="search-icon" />
        </template>
      </a-input>
    </div>

    <!-- 对话列表 -->
    <div class="conversation-list">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <a-spin size="small" />
        <span class="loading-text">加载中...</span>
      </div>

      <!-- 对话项 -->
      <div v-else-if="filteredConversations.length > 0" class="conversation-items">
        <div
          v-for="conversation in filteredConversations"
          :key="conversation.id"
          class="conversation-item"
          :class="{ 'active': conversation.id === activeConversationId }"
          @click="selectConversation(conversation)"
        >
          <div class="conversation-avatar">
            <a-avatar 
              :size="32" 
              :style="{ 
                background: 'linear-gradient(135deg, #6366f1, #8b5cf6)',
                fontSize: '14px',
                fontWeight: '600'
              }"
            >
              {{ conversation.roleName?.[0] || 'R' }}
            </a-avatar>
          </div>
          
          <div class="conversation-content">
            <div class="conversation-header">
              <div class="conversation-title">{{ conversation.title }}</div>
              <div class="conversation-actions">
                <div class="conversation-time">{{ formatTime(conversation.lastMessageTime) }}</div>
                <a-button 
                  type="text" 
                  size="small" 
                  class="delete-btn"
                  @click.stop="handleDeleteConversation(conversation)"
                >
                  <template #icon>
                    <DeleteOutlined />
                  </template>
                </a-button>
              </div>
            </div>
            
            <div class="conversation-meta">
              <div class="role-name">{{ conversation.roleName }}</div>
            </div>
            
            <div class="last-message">{{ conversation.lastMessage }}</div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <HistoryOutlined class="empty-icon" />
        <div class="empty-text">
          {{ searchKeyword ? '未找到匹配的对话' : '暂无历史对话' }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Modal } from 'ant-design-vue'
import { HistoryOutlined, SearchOutlined, ReloadOutlined, DeleteOutlined } from '@ant-design/icons-vue'

// 定义对话类型
interface Conversation {
  id: string
  title: string
  roleId: string
  roleName: string
  lastMessage: string
  lastMessageTime: string
  createdAt: string
}

// Props
interface Props {
  conversations: Conversation[]
  loading?: boolean
  activeConversationId?: string | null
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  activeConversationId: null
})

// Emits
const emit = defineEmits<{
  selectConversation: [conversation: Conversation]
  refresh: []
  deleteConversation: [conversationId: string]
}>()

// 响应式数据
const searchKeyword = ref('')

// 计算属性
const filteredConversations = computed(() => {
  if (!searchKeyword.value.trim()) {
    return props.conversations
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  return props.conversations.filter(conversation =>
    conversation.title.toLowerCase().includes(keyword) ||
    conversation.roleName.toLowerCase().includes(keyword) ||
    conversation.lastMessage.toLowerCase().includes(keyword)
  )
})

// 方法
const selectConversation = (conversation: Conversation) => {
  emit('selectConversation', conversation)
}

const refreshConversations = () => {
  emit('refresh')
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

// 删除会话处理函数
const handleDeleteConversation = (conversation: Conversation) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除与"${conversation.roleName}"的对话"${conversation.title}"吗？此操作不可撤销。`,
    okText: '删除',
    cancelText: '取消',
    okType: 'danger',
    onOk() {
      emit('deleteConversation', conversation.id)
    }
  })
}

// 时间格式化函数
const formatTime = (timeStr: string) => {
  if (!timeStr) return ''
  
  const now = new Date()
  // 为时间添加8小时时区偏移
  const time = new Date(new Date(timeStr).getTime() )
  const diffMs = now.getTime() - time.getTime()
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    return '今天'
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return time.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric'
    })
  }
}
</script>

<style scoped>
.conversation-sidebar {
  width: 300px;
  height: 100%;
  background: #fff;
  border-right: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  padding: 4px 16px;
}

/* 侧边栏头部 */
.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  color: #6366f1;
  font-size: 16px;
}

.title-text {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
}

.header-actions {
  display: flex;
  align-items: center;
}

.refresh-btn {
  color: #666;
  transition: color 0.2s ease;
}

.refresh-btn:hover {
  color: #6366f1;
}

/* 搜索框 */
.search-container {
  padding: 12px 16px;
  /* border-bottom: 1px solid #f0f0f0; */
}

.search-input {
  border-radius: 6px;
}

.search-icon {
  color: #999;
}

/* 对话列表 */
.conversation-list {
  flex: 1;
  overflow-y: auto;
}

.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 24px;
  color: #666;
}

.loading-text {
  font-size: 14px;
}

.conversation-items {
  padding: 8px 0;
}

.conversation-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-left: 3px solid transparent;
}

.conversation-item:hover {
  background: #f8fafc;
}

.conversation-item.active {
  background: #f0f4ff;
  border-left-color: #6366f1;
}

.conversation-avatar {
  flex-shrink: 0;
  margin-top: 2px;
}

.conversation-content {
  flex: 1;
  min-width: 0;
}

.conversation-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 4px;
}

.conversation-title {
  font-size: 14px;
  font-weight: 500;
  color: #1a1a1a;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  margin-right: 8px;
}

.conversation-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.conversation-time {
  font-size: 12px;
  color: #999;
  flex-shrink: 0;
}

.delete-btn {
  opacity: 0;
  transition: all 0.2s ease;
  color: #999;
  padding: 2px;
  min-width: 24px;
  height: 24px;
  border-radius: 4px;
}

.delete-btn:hover {
  color: #ff4d4f;
  background: rgba(255, 77, 79, 0.1);
}

.conversation-item:hover .delete-btn {
  opacity: 1;
}

.conversation-item.active .delete-btn {
  opacity: 1;
}

.conversation-meta {
  margin-bottom: 4px;
}

.role-name {
  font-size: 12px;
  color: #6366f1;
  font-weight: 500;
}

.last-message {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 24px;
  color: #999;
}

.empty-icon {
  font-size: 32px;
  margin-bottom: 12px;
  color: #d9d9d9;
}

.empty-text {
  font-size: 14px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .conversation-sidebar {
    width: 280px;
  }
  
  .conversation-item {
    padding: 10px 12px;
  }
  
  .sidebar-header {
    padding: 12px;
  }
  
  .search-container {
    padding: 8px 12px;
  }
}
</style>